'use strict';

const { Controller } = require('egg');
const path  = require('path');
const fs =  require('fs');
const mkdirp = require('mkdirp');
const moment = require('moment');
const sendToWormhole = require('stream-wormhole');
const toArray = require('stream-to-array');
const api = "http://120.48.87.115:7001/"
//const api = "http://127.0.0.1:7001/"
class UploadController extends Controller {
  async upload() {
    const { ctx } = this;
    // 需要前往 config/config.default.js 设置 config.multipart 的 mode 属性为 file
    const file = ctx.request.files[0];
    // 声明存放资源的路径
    let uploadDir = '';
    let resFile = '';
    try {
      // ctx.request.files[0] 表示获取第一个文件，若前端上传多个文件则可以遍历这个数组对象
      const f = fs.readFileSync(file.filepath);
      // 1.获取当前日期
      const day = moment(new Date()).format('YYYYMMDD');
      // 2.创建图片保存的路径
      const dir = path.join(this.config.uploadDir, day);
      const date = Date.now(); // 毫秒数
      const create_time = moment().format("YYYY-MM-DD HH:mm");
      const update_time = moment().format("YYYY-MM-DD HH:mm");
      await mkdirp(dir); // 不存在就创建目录
      // 返回图片保存的路径
      uploadDir = path.join(dir, date + path.extname(file.filename));
      // decodeURI是为了中文乱码
      resFile = await ctx.model.Files.create({h_file_url:api + uploadDir,create_time,update_time});
      //id = await ctx.service.upload.add({ img_url: api + uploadDir, filename: decodeURI(file.filename) });
      // 写入文件夹
      fs.writeFileSync(uploadDir, f);
    } catch (e) {
      // 清除临时文件
      ctx.cleanupRequestFiles();
    }

    ctx.body = {
      code: "1",
      msg: '上传成功',
      data: uploadDir.replace(/app/g, ''),
      file:resFile,
    };
  }
  async uploadStream() {
    const stream = await this.ctx.getFileStream();
    const {
      filename
    } = stream;
    const day = moment(new Date()).format("YYYYMMDD");
    const dir = path.join(this.config.uploadDir, day);
    let buf;
    let uploadDir = "";
    try {
      await mkdirp(dir); // 不存在就创建目录
      uploadDir = path.join(dir, filename);
      console.log(uploadDir,'uploadDir')
      const streams = fs.createWriteStream(uploadDir, {
        flags: "a",
      });
      const parts = await toArray(stream);
      buf = Buffer.concat(parts);
      streams.write(buf);

      // 当 chunk === chunks ， 证明已经文件已经上传完毕 ， 可以直接写入数据库
      // if (chunk === chunks) {
      //   console.log("上传数据库");
      // }
    } catch (e) {
      console.log(e,'eee')
      await sendToWormhole(stream);
      ctx.cleanupRequestFiles();
      throw e;
    }
    this.ctx.body = {
      code: "1",
      msg: "上传成功",
      data: api+uploadDir,
    };
  }

  async getUrlByIds(){
    const { ctx } = this;
    const {ids} = ctx.request.body;
    console.log(ids,'ids')
    const result = await this.ctx.model.Files.findAll({ where: { h_filesid: ids } })
    if(result){
      ctx.body = {
        code: "1",
        msg: '查询成功',
        data:result
      };
    }else{
      ctx.body = {
        code: "0",
        msg: '查询失败'
      };
    }
    
  }
}

module.exports = UploadController;